<template>
  <div class="app-container">
    <!-- 功能状态卡片 -->
    <el-card shadow="never" class="status-card">
      <div slot="header" class="card-header">
        <span>微信发货信息管理功能状态</span>
        <el-tag :type="configForm.enabled ? 'success' : 'danger'" size="small">
          {{ configForm.enabled ? '已启用' : '未启用' }}
        </el-tag>
      </div>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="status-item">
            <div class="status-title">功能状态</div>
            <div class="status-value">{{ configForm.enabled ? '启用' : '禁用' }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="status-item">
            <div class="status-title">自动上传</div>
            <div class="status-value">{{ configForm.autoUpload ? '开启' : '关闭' }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="status-item">
            <div class="status-title">重试次数</div>
            <div class="status-value">{{ configForm.retryTimes }} 次</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 配置表单 -->
    <el-card shadow="never" style="margin-top: 20px;">
      <div slot="header">
        <span>微信发货配置</span>
      </div>
      
      <el-form ref="configForm" :model="configForm" :rules="rules" label-width="150px">
        <el-form-item label="启用功能" prop="enabled">
          <el-switch
            v-model="configForm.enabled"
            active-text="启用"
            inactive-text="禁用">
          </el-switch>
          <div class="form-tip">启用后，发货时会自动同步信息到微信小程序平台</div>
        </el-form-item>

        <el-form-item label="自动上传" prop="autoUpload">
          <el-switch
            v-model="configForm.autoUpload"
            active-text="开启"
            inactive-text="关闭"
            :disabled="!configForm.enabled">
          </el-switch>
          <div class="form-tip">开启后，发货时自动上传到微信，关闭则需要手动上传</div>
        </el-form-item>

        <el-form-item label="特殊模式" prop="specialMode">
          <el-radio-group v-model="configForm.specialMode" :disabled="!configForm.enabled">
            <el-radio :label="1">普通模式</el-radio>
            <el-radio :label="2">特殊模式</el-radio>
          </el-radio-group>
          <div class="form-tip">特殊模式用于处理特殊发货场景</div>
        </el-form-item>

        <el-form-item label="重试次数" prop="retryTimes">
          <el-input-number
            v-model="configForm.retryTimes"
            :min="0"
            :max="10"
            :disabled="!configForm.enabled">
          </el-input-number>
          <div class="form-tip">上传失败时的重试次数，0表示不重试</div>
        </el-form-item>

        <el-form-item label="重试间隔" prop="retryInterval">
          <el-input-number
            v-model="configForm.retryInterval"
            :min="10"
            :max="300"
            :disabled="!configForm.enabled">
          </el-input-number>
          <span style="margin-left: 10px;">秒</span>
          <div class="form-tip">重试间隔时间，单位秒</div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveConfig" :loading="saving">保存配置</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 使用说明 -->
    <el-card shadow="never" style="margin-top: 20px;">
      <div slot="header">
        <span>使用说明</span>
      </div>
      
      <div class="usage-guide">
        <h4>功能介绍</h4>
        <p>微信发货信息管理功能用于将商城的发货信息同步到微信小程序平台，确保用户在微信小程序中能够及时收到发货通知。</p>
        
        <h4>使用步骤</h4>
        <ol>
          <li>启用微信发货信息管理功能</li>
          <li>配置相关参数（自动上传、重试次数等）</li>
          <li>在订单发货时，系统会自动上传发货信息到微信平台</li>
          <li>用户在微信小程序中收到发货通知</li>
        </ol>
        
        <h4>注意事项</h4>
        <ul>
          <li>需要确保微信小程序配置正确</li>
          <li>用户必须通过微信小程序下单才能收到发货通知</li>
          <li>建议开启自动上传和重试功能，提高成功率</li>
        </ul>
      </div>
    </el-card>
  </div>
</template>

<script>
import { 
  getWechatShippingConfigApi, 
  updateWechatShippingConfigApi,
  isWechatShippingEnabledApi 
} from '@/api/wechatShipping'

export default {
  name: 'WechatShippingConfig',
  data() {
    return {
      loading: false,
      testing: false,
      showApiDoc: false,
      activeHelp: ['1'],
      configForm: {
        enabled: false,
        autoUpload: true,
        specialMode: 1,
        retryTimes: 3,
        retryInterval: 30
      },
      originalConfig: {},
      uploadTiming: 'immediate',
      supportedTypes: ['express', 'delivery', 'virtual'],
      batchUpload: true,
      failureNotification: true,
      logLevel: 'info',
      operationLogs: [],
      accessSchedule: [
        {
          batch: '第一批',
          scope: '珠宝玉石、3C数码、预售商品、新成立企业',
          example: '数码产品、珠宝首饰'
        },
        {
          batch: '第二批',
          scope: '箱包皮具、服饰、美妆、家电等',
          example: '服装鞋帽、化妆品'
        },
        {
          batch: '第三批',
          scope: '食品饮料、生鲜、家装建材等',
          example: '食品生鲜、家居用品'
        },
        {
          batch: '第四批',
          scope: '其他实物电商类小程序',
          example: '其他商品类别'
        }
      ],
      apiList: [
        {
          name: 'uploadShippingInfo',
          method: 'POST',
          url: '/admin/store/order/wechat/upload',
          description: '手动上传微信发货信息'
        },
        {
          name: 'getShippingStatus',
          method: 'GET', 
          url: '/admin/wechat/shipping/status',
          description: '查询微信发货状态'
        },
        {
          name: 'updateConfig',
          method: 'POST',
          url: '/admin/wechat/shipping/config',
          description: '更新微信发货配置'
        },
        {
          name: 'retryUpload',
          method: 'POST',
          url: '/admin/wechat/shipping/retry',
          description: '重试上传发货信息'
        }
      ],
      rules: {
        retryTimes: [
          { required: true, message: '请设置重试次数', trigger: 'blur' }
        ],
        retryInterval: [
          { required: true, message: '请设置重试间隔', trigger: 'blur' }
        ]
      },
      saving: false
    }
  },
  mounted() {
    this.loadConfig()
    this.loadOperationLogs()
  },
  methods: {
    async loadConfig() {
      try {
        const res = await getWechatShippingConfigApi()
        this.configForm = { ...res.data }
        this.originalConfig = { ...res.data }
      } catch (error) {
        console.error('加载配置失败:', error)
        // 使用默认配置
        this.initDefaultConfig()
      }
    },

    initDefaultConfig() {
      this.configForm = {
        enabled: false,
        autoUpload: true,
        specialMode: 1,
        retryTimes: 3,
        retryInterval: 30
      }
      this.originalConfig = { ...this.configForm }
    },

    async submitConfig() {
      this.$refs.configForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            await updateWechatShippingConfigApi(this.configForm)
            this.$message.success('配置保存成功')
            this.originalConfig = { ...this.configForm }
            this.addOperationLog('保存配置', '更新微信发货信息管理配置', true)
          } catch (error) {
            this.$message.error('保存失败: ' + error.message)
            this.addOperationLog('保存配置', '保存配置失败: ' + error.message, false)
          } finally {
            this.loading = false
          }
        }
      })
    },

    resetConfig() {
      this.$confirm('确定要重置为上次保存的配置吗？', '确认重置', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.configForm = { ...this.originalConfig }
        this.$refs.configForm.clearValidate()
        this.$message.success('配置已重置')
      })
    },

    async testConnection() {
      this.testing = true
      try {
        const res = await isWechatShippingEnabledApi()
        this.$message.success('连接测试成功')
        this.addOperationLog('测试连接', '微信发货服务连接正常', true)
      } catch (error) {
        this.$message.error('连接测试失败: ' + error.message)
        this.addOperationLog('测试连接', '连接失败: ' + error.message, false)
      } finally {
        this.testing = false
      }
    },

    handleEnabledChange(value) {
      if (!value) {
        this.$confirm(
          '禁用微信发货信息管理功能后，将不会自动上传发货信息到微信平台，可能影响用户体验和资金结算。确定要禁用吗？',
          '确认禁用',
          {
            confirmButtonText: '确定禁用',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          this.addOperationLog('禁用功能', '禁用微信发货信息管理功能', true)
        }).catch(() => {
          this.configForm.enabled = true
        })
      } else {
        this.addOperationLog('启用功能', '启用微信发货信息管理功能', true)
      }
    },

    loadOperationLogs() {
      // 模拟操作日志数据
      this.operationLogs = [
        {
          time: Date.now() - 1000 * 60 * 30,
          action: '配置更新',
          description: '更新自动上传设置',
          success: true
        },
        {
          time: Date.now() - 1000 * 60 * 60 * 2,
          action: '连接测试',
          description: '测试微信API连接',
          success: true
        }
      ]
    },

    addOperationLog(action, description, success) {
      this.operationLogs.unshift({
        time: Date.now(),
        action,
        description,
        success
      })
      // 最多保留10条记录
      if (this.operationLogs.length > 10) {
        this.operationLogs.pop()
      }
    },

    formatTime(timestamp) {
      return new Date(timestamp).toLocaleString()
    },

    saveConfig() {
      this.$refs.configForm.validate((valid) => {
        if (valid) {
          this.saving = true
          // 模拟保存过程
          setTimeout(() => {
            this.saving = false
            this.$message.success('配置保存成功')
            console.log('保存的配置:', this.configForm)
          }, 1000)
        }
      })
    },

    resetForm() {
      this.$refs.configForm.resetFields()
      this.loadConfig()
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.status-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .status-item {
    text-align: center;
    padding: 20px 0;
    
    .status-title {
      color: #999;
      font-size: 14px;
      margin-bottom: 8px;
    }
    
    .status-value {
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }
  }
}

.form-tip {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.usage-guide {
  h4 {
    color: #333;
    margin: 15px 0 10px 0;
  }
  
  p, li {
    color: #666;
    line-height: 1.6;
  }
  
  ol, ul {
    margin: 10px 0 10px 20px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.form-help {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;

  &.inline-help {
    margin-top: 0;
    margin-left: 15px;
    line-height: 40px;
  }

  i {
    margin-right: 4px;
  }
}

.radio-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.help-content {
  line-height: 1.6;
  
  p {
    margin-bottom: 10px;
  }
  
  ul {
    margin: 10px 0;
    padding-left: 20px;
  }
  
  li {
    margin-bottom: 5px;
  }
  
  a {
    color: #409EFF;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

.api-doc {
  .api-list {
    .api-item {
      margin-bottom: 15px;
      
      .api-header {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .api-url {
          margin-left: 10px;
          font-family: 'Courier New', monospace;
          font-weight: bold;
        }
      }
      
      .api-desc {
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

::v-deep .el-divider__text {
  font-weight: 500;
  color: #303133;
}

::v-deep .el-card__header {
  padding: 18px 20px;
}

::v-deep .el-form-item__label {
  font-weight: 500;
}

::v-deep .el-alert__content {
  line-height: 1.5;
}
</style> 